/**
 * Project Name:jiuselu-parent
 * File Name:Sm4GcmUtils.java
 * Package Name:com.fxp.project.jiuselu.commons.sm4
 * Date:2021年12月04日 13:32
 * Copyright (c) 2021, Jason.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.commons.sm4;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

/**
 * ClassName:Sm4GcmUtils<br/>
 * Function: 国密算法加密<br/>
 * Date:2021年12月04日 13:32<br/>
 *
 * @author Jason.Wang
 * @version 1.0.0
 * @see
 * @since JDK 8
 */
public class Sm4GcmUtils {
    static {
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    /**
     * 解密
     *
     * @param key
     * @param data
     * @param once
     * @param associatedData
     * @return
     */
    public static String decrypt_GCM_NoPadding(String key, String data, String once, String associatedData) throws Exception {
        Cipher cipher = Cipher.getInstance("SM4/GCM/NoPadding", BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(Base64.decodeBase64(key), "SM4");
        byte[] iv = new byte[12];
        if (StringUtils.isNotEmpty(once)) {
            iv = Base64.decodeBase64(once);
        }
        if (StringUtils.isNotEmpty(associatedData)) {
            byte[] aad = associatedData.getBytes();
            cipher.updateAAD(aad);
        }
        GCMParameterSpec s = new GCMParameterSpec(128, iv);
        cipher.init(Cipher.DECRYPT_MODE, sm4Key, s);
        return new String(cipher.doFinal(Base64.decodeBase64(data)));

    }
}